<template>
  <div class="assistance-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="维权援助" fixed>
      <template #right>
        <van-icon name="search" size="18" @click="showSearch = true" />
      </template>
    </van-nav-bar>

    <!-- 搜索栏 -->
    <van-search
      v-show="showSearch"
      v-model="searchKeyword"
      placeholder="搜索援助机构"
      @search="onSearch"
      @cancel="showSearch = false"
      show-action
    />

    <!-- 地区选择 -->
    <div class="location-selector">
      <div class="selector-item" @click="showLocationPicker = true">
        <van-icon name="location-o" />
        <span>{{ selectedLocation || '选择地区' }}</span>
        <van-icon name="arrow-down" />
      </div>
      <div class="selector-item" @click="showTypeFilter = true">
        <van-icon name="filter-o" />
        <span>{{ selectedTypeText }}</span>
        <van-icon name="arrow-down" />
      </div>
    </div>

    <!-- 快速联系 -->
    <div class="quick-contact">
      <div class="section-title">🚨 紧急求助热线</div>
      <div class="hotline-grid">
        <div class="hotline-item" @click="callHotline('12345')">
          <div class="hotline-icon">📞</div>
          <div class="hotline-info">
            <div class="hotline-name">政府服务热线</div>
            <div class="hotline-number">12345</div>
          </div>
        </div>
        <div class="hotline-item" @click="callHotline('12315')">
          <div class="hotline-icon">🛡️</div>
          <div class="hotline-info">
            <div class="hotline-name">消费者投诉</div>
            <div class="hotline-number">12315</div>
          </div>
        </div>
        <div class="hotline-item" @click="callHotline('12333')">
          <div class="hotline-icon">👷</div>
          <div class="hotline-info">
            <div class="hotline-name">劳动保障</div>
            <div class="hotline-number">12333</div>
          </div>
        </div>
        <div class="hotline-item" @click="callHotline('12348')">
          <div class="hotline-icon">⚖️</div>
          <div class="hotline-info">
            <div class="hotline-name">法律援助</div>
            <div class="hotline-number">12348</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 援助机构列表 -->
    <div class="assistance-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="org in orgList"
            :key="org.id"
            class="org-item"
            @click="goToOrgDetail(org)"
          >
            <div class="org-header">
              <div class="org-name">{{ org.name }}</div>
              <div class="org-type" :class="getTypeClass(org.type)">
                {{ getTypeText(org.type) }}
              </div>
            </div>
            
            <div class="org-info">
              <div class="org-location">
                <van-icon name="location-o" />
                <span>{{ org.province }} {{ org.city }}</span>
              </div>
              <div class="org-scope">{{ org.businessScope }}</div>
            </div>

            <div class="org-contact">
              <div class="contact-item">
                <van-icon name="phone-o" />
                <span>{{ org.phone }}</span>
              </div>
              <div v-if="org.serviceTime" class="contact-item">
                <van-icon name="clock-o" />
                <span>{{ org.serviceTime }}</span>
              </div>
            </div>

            <div class="org-footer">
              <div class="org-tags">
                <span v-if="org.isFree" class="tag free">免费</span>
                <span v-else class="tag paid">收费</span>
                <span v-if="org.rating > 0" class="tag rating">
                  ⭐ {{ org.rating }}分
                </span>
              </div>
              <div class="org-actions">
                <van-button
                  size="small"
                  type="primary"
                  @click.stop="callOrg(org)"
                >
                  立即咨询
                </van-button>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab">
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="chat-o" to="/community">社区</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/templates">工具</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 地区选择器 -->
    <van-popup v-model:show="showLocationPicker" position="bottom">
      <van-area
        :area-list="areaList"
        @confirm="onLocationConfirm"
        @cancel="showLocationPicker = false"
      />
    </van-popup>

    <!-- 类型筛选 -->
    <van-action-sheet
      v-model:show="showTypeFilter"
      :actions="typeFilterOptions"
      @select="onTypeFilterSelect"
      cancel-text="取消"
    />

    <!-- 机构详情弹窗 -->
    <van-popup
      v-model:show="showOrgDetail"
      position="bottom"
      :style="{ height: '70%' }"
      round
      closeable
    >
      <div v-if="selectedOrg" class="org-detail">
        <div class="detail-header">
          <div class="detail-name">{{ selectedOrg.name }}</div>
          <div class="detail-type">{{ getTypeText(selectedOrg.type) }}</div>
        </div>

        <div class="detail-content">
          <!-- 基本信息 -->
          <div class="detail-section">
            <div class="section-title">基本信息</div>
            <div class="info-list">
              <div class="info-item">
                <span class="info-label">地址：</span>
                <span class="info-value">{{ selectedOrg.address }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">电话：</span>
                <span class="info-value">{{ selectedOrg.phone }}</span>
              </div>
              <div v-if="selectedOrg.email" class="info-item">
                <span class="info-label">邮箱：</span>
                <span class="info-value">{{ selectedOrg.email }}</span>
              </div>
              <div v-if="selectedOrg.website" class="info-item">
                <span class="info-label">官网：</span>
                <span class="info-value">{{ selectedOrg.website }}</span>
              </div>
            </div>
          </div>

          <!-- 服务范围 -->
          <div class="detail-section">
            <div class="section-title">服务范围</div>
            <div class="section-content">{{ selectedOrg.businessScope }}</div>
          </div>

          <!-- 服务时间 -->
          <div v-if="selectedOrg.serviceTime" class="detail-section">
            <div class="section-title">服务时间</div>
            <div class="section-content">{{ selectedOrg.serviceTime }}</div>
          </div>
        </div>

        <div class="detail-actions">
          <van-button @click="callOrg(selectedOrg)">电话咨询</van-button>
          <van-button type="primary" @click="addToContacts(selectedOrg)">
            添加联系人
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()

// 响应式数据
const activeTab = ref(2)
const showSearch = ref(false)
const searchKeyword = ref('')
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const showLocationPicker = ref(false)
const showTypeFilter = ref(false)
const showOrgDetail = ref(false)
const selectedOrg = ref(null)

// 筛选条件
const filters = reactive({
  location: '',
  type: 'all'
})

const selectedLocation = ref('')

// 机构列表
const orgList = ref([])

// 筛选选项
const typeFilterOptions = [
  { name: '全部类型', value: 'all' },
  { name: '法律援助中心', value: 1 },
  { name: '律师事务所', value: 2 },
  { name: '政府部门', value: 3 },
  { name: '其他机构', value: 4 }
]

// 地区数据（简化版）
const areaList = ref({
  province_list: {
    110000: '北京市',
    120000: '天津市',
    310000: '上海市',
    440000: '广东省',
    320000: '江苏省',
    330000: '浙江省'
  },
  city_list: {
    110100: '北京市',
    120100: '天津市',
    310100: '上海市',
    440100: '广州市',
    440300: '深圳市',
    320100: '南京市',
    330100: '杭州市'
  },
  county_list: {
    110101: '东城区',
    110102: '西城区',
    440103: '荔湾区',
    440104: '越秀区',
    320102: '玄武区',
    330102: '上城区'
  }
})

// 模拟数据
const mockOrgs = [
  {
    id: 1,
    name: '北京市法律援助中心',
    type: 1,
    province: '北京市',
    city: '北京市',
    district: '西城区',
    address: '北京市西城区广安门南街48号',
    phone: '010-12348',
    email: 'help@bjlegalaid.gov.cn',
    website: 'http://www.bjlegalaid.gov.cn',
    businessScope: '为经济困难的公民提供法律援助，包括法律咨询、代理诉讼、刑事辩护等',
    serviceTime: '周一至周五 9:00-17:00',
    isFree: true,
    rating: 4.8
  },
  {
    id: 2,
    name: '德恒律师事务所',
    type: 2,
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    address: '北京市朝阳区东三环中路1号环球金融中心',
    phone: '010-52682888',
    email: 'info@dehenglaw.com',
    website: 'http://www.dehenglaw.com',
    businessScope: '公司法务、民商事诉讼、知识产权、劳动争议等法律服务',
    serviceTime: '周一至周日 24小时',
    isFree: false,
    rating: 4.6
  },
  {
    id: 3,
    name: '上海市消费者权益保护委员会',
    type: 3,
    province: '上海市',
    city: '上海市',
    district: '黄浦区',
    address: '上海市黄浦区中山南路1号',
    phone: '021-12315',
    email: 'service@shcc315.org.cn',
    website: 'http://www.shcc315.org.cn',
    businessScope: '受理消费者投诉，调解消费纠纷，开展消费教育和监督',
    serviceTime: '周一至周五 9:00-17:00',
    isFree: true,
    rating: 4.5
  }
]

// 计算属性
const selectedTypeText = computed(() => {
  const option = typeFilterOptions.find(item => item.value === filters.type)
  return option ? option.name : '全部类型'
})

// 方法
const getTypeClass = (type) => {
  const classMap = {
    1: 'legal-aid',
    2: 'law-firm',
    3: 'government',
    4: 'other'
  }
  return classMap[type] || 'other'
}

const getTypeText = (type) => {
  const textMap = {
    1: '法律援助',
    2: '律师事务所',
    3: '政府部门',
    4: '其他机构'
  }
  return textMap[type] || '未知'
}

const onRefresh = () => {
  refreshing.value = true
  orgList.value = []
  finished.value = false
  loadOrgs().finally(() => {
    refreshing.value = false
  })
}

const onLoad = () => {
  loadOrgs()
}

const loadOrgs = async () => {
  loading.value = true
  
  // 模拟API请求
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟分页加载
  const startIndex = orgList.value.length
  const pageSize = 10
  let filteredOrgs = mockOrgs
  
  // 根据类型筛选
  if (filters.type !== 'all') {
    filteredOrgs = mockOrgs.filter(org => org.type === filters.type)
  }
  
  // 根据地区筛选
  if (filters.location) {
    filteredOrgs = filteredOrgs.filter(org => 
      org.province.includes(filters.location) || 
      org.city.includes(filters.location)
    )
  }
  
  // 搜索筛选
  if (searchKeyword.value) {
    filteredOrgs = filteredOrgs.filter(org =>
      org.name.includes(searchKeyword.value) ||
      org.businessScope.includes(searchKeyword.value)
    )
  }
  
  const newOrgs = filteredOrgs.slice(startIndex, startIndex + pageSize)
  
  if (newOrgs.length === 0) {
    finished.value = true
  } else {
    orgList.value.push(...newOrgs)
  }
  
  loading.value = false
}

const onSearch = () => {
  orgList.value = []
  finished.value = false
  loadOrgs()
}

const onLocationConfirm = ({ selectedValues }) => {
  selectedLocation.value = selectedValues.join(' ')
  filters.location = selectedValues.join(' ')
  showLocationPicker.value = false
  onRefresh()
}

const onTypeFilterSelect = (action) => {
  filters.type = action.value
  showTypeFilter.value = false
  onRefresh()
}

const callHotline = (number) => {
  showConfirmDialog({
    title: '拨打热线',
    message: `确定要拨打 ${number} 吗？`,
  }).then(() => {
    // 在真实环境中，这里会调用拨号功能
    window.location.href = `tel:${number}`
  }).catch(() => {
    // 用户取消
  })
}

const goToOrgDetail = (org) => {
  selectedOrg.value = org
  showOrgDetail.value = true
}

const callOrg = (org) => {
  showConfirmDialog({
    title: '拨打电话',
    message: `确定要拨打 ${org.phone} 吗？`,
  }).then(() => {
    window.location.href = `tel:${org.phone}`
  }).catch(() => {
    // 用户取消
  })
}

const addToContacts = (org) => {
  // 模拟添加到联系人
  showToast('已添加到联系人')
}

onMounted(() => {
  loadOrgs()
})
</script>

<style scoped>
.assistance-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

.location-selector {
  background: white;
  padding: 12px 16px;
  display: flex;
  gap: 12px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 46px;
  z-index: 99;
}

.selector-item {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #f7f8fa;
  border-radius: 6px;
  font-size: 14px;
  color: #646566;
  cursor: pointer;
}

.quick-contact {
  background: white;
  padding: 16px;
  margin-bottom: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
}

.hotline-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.hotline-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f7f8fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.hotline-item:hover {
  background: #e8f2ff;
}

.hotline-icon {
  font-size: 24px;
}

.hotline-info {
  flex: 1;
}

.hotline-name {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 2px;
}

.hotline-number {
  font-size: 16px;
  color: #1989fa;
  font-weight: 600;
}

.assistance-list {
  padding: 8px 0;
}

.org-item {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
  cursor: pointer;
}

.org-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.org-name {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.org-type {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.org-type.legal-aid {
  background: #f6ffed;
  color: #52c41a;
}

.org-type.law-firm {
  background: #f0f9ff;
  color: #1989fa;
}

.org-type.government {
  background: #fff7e6;
  color: #ff976a;
}

.org-type.other {
  background: #f7f8fa;
  color: #646566;
}

.org-info {
  margin-bottom: 12px;
}

.org-location {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #646566;
  margin-bottom: 6px;
}

.org-scope {
  font-size: 13px;
  color: #969799;
  line-height: 1.4;
}

.org-contact {
  margin-bottom: 12px;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #646566;
  margin-bottom: 4px;
}

.org-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.org-tags {
  display: flex;
  gap: 8px;
}

.tag {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 3px;
}

.tag.free {
  background: #f6ffed;
  color: #52c41a;
}

.tag.paid {
  background: #fff2f0;
  color: #ff4d4f;
}

.tag.rating {
  background: #fff7e6;
  color: #ff976a;
}

.org-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 20px 16px;
  border-bottom: 1px solid #eee;
}

.detail-name {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.detail-type {
  font-size: 14px;
  color: #1989fa;
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section .section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
}

.info-list {
  space-y: 8px;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
}

.info-label {
  width: 60px;
  font-size: 14px;
  color: #646566;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #323233;
}

.section-content {
  font-size: 14px;
  color: #646566;
  line-height: 1.6;
}

.detail-actions {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
}

.detail-actions .van-button {
  flex: 1;
}
</style>